package com.gpstracker.services;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import com.gpstracker.activities.AppPreferencesActivity;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

public class RegistrationService extends Service{

	private static final String tag = "REGISTRATION_SERVICE";
	ArrayList<NameValuePair> nameValuePairs;
	TelephonyManager telephonyManager;
	String dbServer;
	
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		Log.i(tag, "ON_CREATE");

		telephonyManager = (TelephonyManager) getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
		
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
		String name = prefs.getString("name", "");
		String surname = prefs.getString("surname", "");
		String email = prefs.getString("email", "");
		dbServer = prefs.getString("dbserver", "192.168.0.101");
		
		if(name.equals("") || surname.equals("") || email.equals("")){
			Toast.makeText(getApplicationContext(), "please, insert all your data", Toast.LENGTH_SHORT).show();
			Intent intent = new Intent(getApplicationContext(), AppPreferencesActivity.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(intent);
		}
		else {
			
			String imei = prefs.getString("imei", "");
			if(imei.equals(""))
				imei = telephonyManager.getDeviceId();
			
			nameValuePairs = new ArrayList<NameValuePair>();
			nameValuePairs.add(new BasicNameValuePair("name", name));
			nameValuePairs.add(new BasicNameValuePair("surname", surname));
			nameValuePairs.add(new BasicNameValuePair("email", email));
			nameValuePairs.add(new BasicNameValuePair("imei", imei));
			
			Inserter inserter = new Inserter();
			inserter.execute();
				
		}


		this.stopSelf();
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		Log.i(tag, "ON_DESTROY");
	}
	
	private class Inserter extends AsyncTask<String, String, String>{

		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			
			Log.i(tag, "background_task");
			InputStream is = null;
			String result;
			try{
				HttpClient httpclient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost("http://"+dbServer+"/insertUser.php");
				
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				
			}catch(Exception e){
				Log.e("log_tag", "Error in http connection "+e.toString());
			}
			
			//convert response to string
			try{
			    	Log.i(tag , "toString");
					BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
			        StringBuilder sb = new StringBuilder();
			        String line = null;
			        while ((line = reader.readLine()) != null) {
			                sb.append(line + "\n");
			        }
			        is.close();
			 
			        result=sb.toString();
			        
			        Log.i(tag, result);
			        
			}catch(Exception e){
			        Log.e("log_tag", "Error converting result "+e.toString());
			}
			
			return null;
		
		}
	}
}
